package UI;

import DB.*;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.ImageCursor;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.sql.SQLException;
import java.util.*;

public class Service2 {
    //role
    private User user;
    //question
    private Stage stage;
    private ArrayList<Button> buttons = new ArrayList<>();
    private StackPane mainContent;
    private BorderPane root;
    private TableView<Questionlib> table;
    //exam
    private BorderPane pane;
    private List<Questionlib> examQuestions = new ArrayList<>();
    private Map<Integer, String> userAnswers = new HashMap<>();
    private int questionIndex = 0;
    private int correct = 0;
    private int wrong = 0;
    private int unanswer = 0;
    private int remainTime = 2700;
    private Timeline timeline;
    private Label timeLabel;
    private VBox options;
    private Label questionLabel;
    //grade
    private TableView<Answer> grades;
    //topic
    private List<Questionlib> topicQuestionlibs;
    //section
    private List<Questionlib> sectionQuestionlibs;
    //wrong
    private TableView<WrongQuestion> wrongQuestions;
    private List<WrongQuestion> wrongQuestionlibs;
    //highwrong
    private List<WrongQuestion> highWrongQuestions;

    public Service2(Stage stage, User user) {
        this.stage = stage;
        this.user = user;
        initMenu();
    }

    private void initMenu() {
        root = new BorderPane();
        HBox topMenu = addTopBar();
        root.setTop(topMenu);
        VBox leftMenu = addLeftBar();
        root.setLeft(leftMenu);
        mainContent = new StackPane();
        mainContent.getChildren().add(new Label("欢迎进入模拟考试系统"));
        root.setCenter(mainContent);
        setButtonAction(buttons);
        Scene scene = new Scene(root, 1200, 800);
        scene.setCursor(new ImageCursor(new Image("images/Cursor1.png")));
        stage.setScene(scene);
        stage.centerOnScreen();
    }

    private HBox addTopBar() {
        HBox topBar = new HBox();
        topBar.setStyle("-fx-background-color: #2f465e; -fx-padding: 20;");
        topBar.setSpacing(20);

        Label title = new Label("C1科目一模拟考试系统界面");
        title.setStyle("-fx-text-fill: white; -fx-font-size: 20px;");

        HBox userBox = new HBox(10);
        userBox.setAlignment(Pos.CENTER_RIGHT);
        Label userName = new Label("当前用户: " + user.getUserName());
        userName.setStyle("-fx-text-fill: white;");
        Button logout = new Button("退出登录");
        logout.setStyle("-fx-background-color: #e74c3c; -fx-text-fill: white;");
        logout.setOnAction(e -> {
            // 返回登录界面
            stage.close();
            try {
                new LogIn().start(new Stage());
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
        userBox.getChildren().addAll(userName, logout);
        topBar.getChildren().addAll(title, userBox);
        return topBar;
    }

    private VBox addLeftBar() {
        VBox leftMenu = new VBox();
        leftMenu.setStyle("-fx-background-color: #d6d9de;-fx-text-fill: #141111;");
        leftMenu.setSpacing(20);
        leftMenu.setMinWidth(150);
        leftMenu.setMaxWidth(400);

        String[] Menus = {"题库管理",
                "模拟考试",
                "历史成绩",
                "专项练习",
                "章节练习",
                "易错题练习",
                "错题本"
        };

        for (int i = 0; i < Menus.length; i++) {
            Button button = new Button(Menus[i]);
            button.setStyle("-fx-text-fill: Black;-fx-background-color: #88b0db;");
            button.setMaxWidth(Double.MAX_VALUE);
            button.setAlignment(Pos.TOP_CENTER);
            leftMenu.getChildren().add(button);
            buttons.add(button);
        }

        return leftMenu;
    }

    private void setButtonAction(ArrayList<Button> buttons) {

        //题库管理
        Button quesButton = buttons.getFirst();
        quesButton.setOnAction(actionEvent -> {
            if (user.getRole().equals("管理员")) {
                createTableUI(mainContent);
                refreshTable();
            } else {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText("温馨提示");
                alert.setContentText("您不是管理员，没有这个权限哈");
                alert.showAndWait();
            }
        });

        //模拟考试
        Button examButton = buttons.get(1);
        examButton.setOnAction(actionEvent -> {
            System.out.println("exam");
            try {
                createExamUI(mainContent);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        });

        //历史成绩
        Button gradeButton = buttons.get(2);
        gradeButton.setOnAction(actionEvent -> {
            System.out.println("grade");
            System.out.println("当前用户是" + user.getUserName());
            createHistoryGradeUI(mainContent);
        });

        //专项练习
        Button topicButton = buttons.get(3);
        topicButton.setOnAction(actionEvent -> {
            System.out.println("topic");
            try {
                createTopicUI(mainContent);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });

        //章节练习
        Button sectionButton = buttons.get(4);
        sectionButton.setOnAction(actionEvent -> {
            System.out.println("section");
            try {
                createSectionUI(mainContent);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });

        //易错题练习
        Button highButton = buttons.get(5);
        highButton.setOnAction(actionEvent -> {
            System.out.println("highwrong");
            try {
                createHighUI(mainContent);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });


        //错题本
        Button wrongButton = buttons.get(6);
        wrongButton.setOnAction(actionEvent -> {
            System.out.println("wrong");
            createWrongUI(mainContent);
        });
    }


    //题库表格界面
    private void createTableUI(StackPane rightPane) {
        VBox rightBox = new VBox();
        rightBox.setSpacing(10);
        VBox tableBox = new VBox();
        tableBox.setSpacing(10);
        tableBox.setStyle("-fx-padding: 15;");
        table = new TableView<>();
        table.setMinHeight(100);
        TableColumn<Questionlib, Integer> idColumn = new TableColumn<>("题目编号");
        idColumn.setMinWidth(50);
        idColumn.setCellValueFactory(cellData ->
                cellData.getValue().idPro().asObject()
        );
        TableColumn<Questionlib, String> quesColumn = new TableColumn<>("题目");
        quesColumn.setMinWidth(500);
        quesColumn.setCellValueFactory(cellData ->
                cellData.getValue().questionPro()
        );
        TableColumn<Questionlib, String> typeColumn = new TableColumn<>("题型");
        typeColumn.setMinWidth(100);
        typeColumn.setCellValueFactory(cellData ->
                cellData.getValue().typePro()
        );
        TableColumn<Questionlib, String> sectionColumn = new TableColumn<>("章节");
        sectionColumn.setMinWidth(200);
        sectionColumn.setCellValueFactory(cellData ->
                cellData.getValue().sectionPro()
        );
        TableColumn<Questionlib, String> topicColumn = new TableColumn<>("范畴");
        topicColumn.setMinWidth(200);
        topicColumn.setCellValueFactory(cellData ->
                cellData.getValue().topicPro()
        );
        TableColumn<Questionlib, String> answerColumn = new TableColumn<>("答案");
        answerColumn.setMinWidth(50);
        answerColumn.setCellValueFactory(cellData ->
                cellData.getValue().answerPro()
        );
        table.getColumns().addAll(idColumn, quesColumn, typeColumn, sectionColumn, topicColumn, answerColumn);
        HBox buttonBox = addUIButton();
        tableBox.getChildren().add(table);
        rightBox.getChildren().addAll(buttonBox, tableBox);
        rightPane.getChildren().clear();
        rightPane.getChildren().addAll(rightBox);
        root.setCenter(rightPane);
    }

    private HBox addUIButton() {
        HBox buttonBox = new HBox();
        buttonBox.setSpacing(10);
        buttonBox.setStyle("-fx-padding: 15");
        Button addButton = new Button("增加题目");
        Button deleteButton = new Button("删除题目");
        Button modifyButton = new Button("修改题目");
        Button selectButton = new Button("查找题目");
        addButton.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        deleteButton.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        modifyButton.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        selectButton.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");

        addButton.setOnAction(event -> {
            System.out.println("增加");
            addFunction();
        });

        deleteButton.setOnAction(event -> {
            System.out.println("删除");
            deleteFunction();
        });

        modifyButton.setOnAction(event -> {
            System.out.println("更改");
            modifyFunction();
        });

        selectButton.setOnAction(event -> {
            System.out.println("查询");
            selectFunction();
        });
        buttonBox.getChildren().addAll(addButton, deleteButton, modifyButton, selectButton);

        return buttonBox;
    }

    //增
    private void addFunction() {
        Dialog<Questionlib> addDialog = new Dialog<>();
        addDialog.setTitle("添加题目");
        addDialog.setHeaderText("请输入您要添加的题目信息:");
        addDialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        Label quesLabel = new Label("题目内容");
        grid.add(quesLabel, 0, 1);
        TextArea quesField = new TextArea();
        grid.add(quesField, 1, 1);

        Label typeLabel = new Label("题目类型");
        grid.add(typeLabel, 0, 2);
        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.getItems().addAll("单选题", "多选题", "判断题");
        comboBox.setValue("单选题");
        grid.add(comboBox, 1, 2);

        Label secLabel = new Label("所属章节");
        grid.add(secLabel, 0, 3);
        ComboBox<String> secField = new ComboBox<>();
        secField.getItems().addAll("1.驾驶证和机动车管理规定",
                "2.道路通行条件及通行规定",
                "3.道路交通安全违法行为及处罚",
                "4.道路交通事故处理相关规定",
                "5.机动车基础知识",
                "6.河南地方题");
        secField.setValue("1.驾驶证和机动车管理规定");
        grid.add(secField, 1, 3);

        Label topicLabel = new Label("所属范畴");
        grid.add(topicLabel, 0, 4);
        ComboBox<String> topicField = new ComboBox<>();
        topicField.getItems().addAll("文字题", "图片题", "罚款题", "记分题");
        topicField.setValue("文字题");
        grid.add(topicField, 1, 4);

        Label answerLabel = new Label("答案");
        grid.add(answerLabel, 0, 5);
        TextField answerField = new TextField();
        answerField.setPromptText("格式只允许出现大写字母，无标点");
        grid.add(answerField, 1, 5);

        addDialog.getDialogPane().setContent(grid);
        addDialog.setResultConverter(buttonType -> {
            if (buttonType == ButtonType.OK) {
                try {
                    int id = TestLib.addQuestion(quesField.getText(), comboBox.getValue(), secField.getValue(), topicField.getValue(), answerField.getText());
                    Questionlib question = new Questionlib();
                    question.setId(id);
                    question.setQuestion(quesField.getText());
                    question.setSection(secField.getValue());
                    question.setType(comboBox.getValue());
                    question.setTopic(topicField.getValue());
                    question.setAnswer(answerField.getText());
                    return question;
                } catch (SQLException e) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("添加失败提示");
                    alert.setContentText("由于输入格式有误或其他问题,\n添加失败");
                    alert.showAndWait();
                    return null;
                }
            }
            return null;
        });
        addDialog.showAndWait().ifPresent(questionlib -> {
                    try {
                        refreshTable();
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setContentText("题目" + questionlib.getId() + "添加成功");
                        alert.showAndWait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );

    }

    //删
    private void deleteFunction() {
        Questionlib question = table.getSelectionModel().getSelectedItem();
        if (question != null) {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("删除提示");
            alert.setContentText("确认删除这个题目吗？");

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK) {
                try {
                    TestLib.deleteQuestion(question.getId());
                    Alert alert1 = new Alert(Alert.AlertType.INFORMATION);
                    alert1.setContentText("删除成功");
                    refreshTable();
                } catch (SQLException e) {
                    Alert alert1 = new Alert(Alert.AlertType.INFORMATION);
                    alert1.setContentText("删除失败，请重新操作");
                    throw new RuntimeException(e);
                }
            }
        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("请先点击您想删除的题目");
            alert.showAndWait();
        }
    }

    private void refreshTable() {
        try {
            table.getItems().clear();
            List<Questionlib> questions = TestLib.getQuestions();
            table.getItems().addAll(questions);
        } catch (SQLException e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("添加失败提示");
            alert.setContentText("由于输入格式有误或其他问题,\n添加失败");
            alert.showAndWait();
        }
    }

    //改
    private void modifyFunction() {
        Questionlib question = table.getSelectionModel().getSelectedItem();
        Dialog<Questionlib> addDialog = null;
        if (question != null) {
            addDialog = new Dialog<>();
            addDialog.setTitle("更改题目");
            addDialog.setHeaderText("请输入您要更改的题目信息:");
            addDialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

            GridPane grid = new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new Insets(20, 150, 10, 10));

            Label quesLabel = new Label("题目内容");
            grid.add(quesLabel, 0, 1);
            TextArea quesField = new TextArea();
            grid.add(quesField, 1, 1);

            Label typeLabel = new Label("题目类型");
            grid.add(typeLabel, 0, 2);
            ComboBox<String> comboBox = new ComboBox<>();
            comboBox.getItems().addAll("单选题", "多选题", "判断题");
            comboBox.setValue("单选题");
            grid.add(comboBox, 1, 2);

            Label secLabel = new Label("所属章节");
            grid.add(secLabel, 0, 3);
            ComboBox<String> secField = new ComboBox<>();
            secField.getItems().addAll("1.驾驶证和机动车管理规定",
                    "2.道路通行条件及通行规定",
                    "3.道路交通安全违法行为及处罚",
                    "4.道路交通事故处理相关规定",
                    "5.机动车基础知识",
                    "6.河南地方题");
            secField.setValue("1.驾驶证和机动车管理规定");
            grid.add(secField, 1, 3);

            Label topicLabel = new Label("所属范畴");
            grid.add(topicLabel, 0, 4);
            ComboBox<String> topicField = new ComboBox<>();
            topicField.getItems().addAll("文字题", "图片题", "罚款题", "记分题");
            topicField.setValue("文字题");
            grid.add(topicField, 1, 4);

            Label answerLabel = new Label("答案");
            grid.add(answerLabel, 0, 5);
            TextField answerField = new TextField();
            answerField.setPromptText("格式只允许出现大写字母，无标点");
            grid.add(answerField, 1, 5);

            addDialog.getDialogPane().setContent(grid);
            addDialog.setResultConverter(buttonType -> {
                if (buttonType == ButtonType.OK) {
                    try {
                        TestLib.modifyQuestion(question.getId(), quesField.getText(), comboBox.getValue(), secField.getValue(), topicField.getValue(), answerField.getText());
                        question.setQuestion(quesField.getText());
                        question.setType(comboBox.getValue());
                        question.setSection(secField.getValue());
                        question.setTopic(topicField.getValue());
                        question.setAnswer(answerField.getText());
                        return question;
                    } catch (SQLException e) {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setContentText("更改失败，可能是格式有误");
                        alert.showAndWait();

                        return null;
                    }
                }
                return null;
            });

        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("请先点击表格中您想修改的题目");
            alert.showAndWait();
        }
        addDialog.showAndWait().ifPresent(questionlib -> {
                    try {
                        refreshTable();
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setContentText("题目" + questionlib.getId() + "更改成功");
                        alert.showAndWait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );

    }

    //查
    private void selectFunction() {
        Dialog<Questionlib> dialog = new Dialog<>();
        dialog.setTitle("查询题目");
        dialog.setHeaderText("请输入您要查询的题目编号");
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK);
        TextField idField = new TextField();
        idField.setPromptText("要表格中已存在的题目编号哈");
        Button select = new Button("查询");
        HBox hbox = new HBox(10);
        hbox.getChildren().addAll(idField, select);
        TableView<Questionlib> tableSingle = new TableView<>();
        tableSingle.setMinHeight(500);
        TableColumn<Questionlib, Integer> idColumn = new TableColumn<>("题目编号");
        idColumn.setMinWidth(50);
        idColumn.setCellValueFactory(cellData ->
                cellData.getValue().idPro().asObject()
        );
        TableColumn<Questionlib, String> quesColumn = new TableColumn<>("题目");
        quesColumn.setMinWidth(500);
        quesColumn.setCellValueFactory(cellData ->
                cellData.getValue().questionPro()
        );
        TableColumn<Questionlib, String> typeColumn = new TableColumn<>("题型");
        typeColumn.setMinWidth(100);
        typeColumn.setCellValueFactory(cellData ->
                cellData.getValue().typePro()
        );
        TableColumn<Questionlib, String> sectionColumn = new TableColumn<>("章节");
        sectionColumn.setMinWidth(200);
        sectionColumn.setCellValueFactory(cellData ->
                cellData.getValue().sectionPro()
        );
        TableColumn<Questionlib, String> topicColumn = new TableColumn<>("范畴");
        topicColumn.setMinWidth(200);
        topicColumn.setCellValueFactory(cellData ->
                cellData.getValue().topicPro()
        );
        TableColumn<Questionlib, String> answerColumn = new TableColumn<>("答案");
        answerColumn.setMinWidth(50);
        answerColumn.setCellValueFactory(cellData ->
                cellData.getValue().answerPro()
        );
        tableSingle.getColumns().addAll(idColumn, quesColumn, typeColumn, sectionColumn, topicColumn, answerColumn);
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(20));
        vbox.getChildren().addAll(hbox, tableSingle);
        dialog.getDialogPane().setContent(vbox);

        select.setOnAction(event -> {
            searchId(tableSingle, idField.getText());
        });


        dialog.showAndWait();
    }

    private void searchId(TableView<Questionlib> tableView, String idField) {
        try {
            if (idField.isEmpty()) {
                return;
            }
            int id = Integer.parseInt(idField);
            Questionlib question = TestLib.selectQuestion(id);

            tableView.getItems().clear();
            if (question != null) {
                tableView.getItems().add(question);
            } else {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("请输入有效题目编号");
                alert.showAndWait();
            }
        } catch (NumberFormatException e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("请输入有效的题目编号，光数字");
            alert.showAndWait();
        } catch (SQLException e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("没有相关题目编号");
            alert.showAndWait();
            e.printStackTrace();
        }


    }


    //模拟考试
    private void createExamUI(StackPane rightPane) throws SQLException {
        initData();
        startExam();
        pane = new BorderPane();
        pane.setStyle("-fx-background-color: #f2eded");
        pane.setMinWidth(1050);

        HBox topBar = new HBox(20);
        timeLabel = new Label("剩余时间: 45:00");
        timeLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #2f465e;");
        questionLabel = new Label("第1/100题");
        questionLabel.setStyle("-fx-font-size: 14px;");
        topBar.getChildren().addAll(timeLabel, questionLabel);
        pane.setTop(topBar);

        VBox questionArea = new VBox(15);
        questionArea.setStyle("-fx-text-alignment: center;");
        questionArea.setPadding(new Insets(20, 100, 20, 40));
        Label questionText = new Label();
        questionText.setWrapText(true);
        questionText.setStyle("-fx-font-size: 16px;-fx-text-alignment: center");
        options = new VBox(10);
        options.setPadding(new Insets(10, 0, 10, 20));
        questionArea.getChildren().addAll(questionText, options);
        ScrollPane scrollPane = new ScrollPane(questionArea);
        scrollPane.setFitToWidth(true);
        pane.setCenter(scrollPane);

        HBox bottomBox = switchQuestion();
        pane.setBottom(bottomBox);

        showQuestion(1);

        rightPane.getChildren().clear();
        rightPane.getChildren().add(pane);
    }

    private void initData() throws SQLException {
        examQuestions = new ArrayList<>();
        userAnswers = new HashMap<>();
        correct = 0;
        wrong = 0;
        unanswer=0;
        List<Questionlib> realQuestions = TestLib.getQuestions();
        Collections.shuffle(realQuestions);
        int realCount = Math.min(realQuestions.size(), 100);
        examQuestions.addAll(realQuestions.subList(0, realCount));

        if (realCount < 100) {
            Random r = new Random();
            String[] types = {"单选题", "多选题", "判断题"};
            String[] topics = {"文字题", "图片题", "罚款题", "记分题"};
            String[] sections = {"1.驾驶证和机动车管理规定",
                    "2.道路通行条件及通行规定",
                    "3.道路交通安全违法行为及处罚",
                    "4.道路交通事故处理相关规定",
                    "5.机动车基础知识",
                    "6.河南地方题"};
            for (int i = realCount; i < 100; i++) {
                Questionlib questionlib = new Questionlib();
                questionlib.setId(i + 1);
                questionlib.setType(types[r.nextInt(types.length)]);
                questionlib.setTopic(topics[r.nextInt(topics.length)]);
                questionlib.setSection(sections[r.nextInt(sections.length)]);
                questionlib.setQuestion("本题用于测试题目哈，随便选吧");
                createAnswers(questionlib);
                examQuestions.add(questionlib);
            }
        }
    }

    private void showQuestion(int index) {
        if (index < 1 || index > 100) return;

        questionIndex = index;
        Questionlib question = examQuestions.get(index - 1);
        questionLabel.setText(String.format("第 %d/100 题", index));

        options.getChildren().clear();
        String[] singleAnswer = {"A", "B", "C", "D"};
        Label content = new Label(question.getQuestion());
        content.setStyle("-fx-font-size: 16px;-fx-text-alignment: center");
        options.getChildren().add(content);

        if (question.getType().equals("单选题")) {
            ToggleGroup group = new ToggleGroup();
            for (int i = 0; i < singleAnswer.length; i++) {
                RadioButton rb = new RadioButton(singleAnswer[i]);
                rb.setToggleGroup(group);
                if (userAnswers.containsKey(index - 1)) {
                    rb.setSelected(rb.getText().startsWith(userAnswers.get(index - 1)));
                }
                rb.setOnAction(e -> handleExamAnswer(index - 1, rb.getText(), question));
                options.getChildren().add(rb);
            }
        } else if (question.getType().equals("多选题")) {
            Label confirmLabel=new Label("请在选完之后按确认选择");
            List<CheckBox> checkBoxes = new ArrayList<>();
            for (int i = 0; i < singleAnswer.length; i++) {
                CheckBox cb = new CheckBox(singleAnswer[i]);
                if (userAnswers.containsKey(index - 1)) {
                    String answer = userAnswers.get(index - 1);
                    cb.setSelected(answer.contains(cb.getText()));
                }
                checkBoxes.add(cb);
                options.getChildren().add(cb);
            }
            Button confirm = new Button("确认选择");
            confirm.setStyle("-fx-background-color: #2f465e; -fx-text-fill: #edeef4;");
            confirm.setOnAction(e -> {
                StringBuilder sb = new StringBuilder();
                for (CheckBox checkBox : checkBoxes) {
                    if (checkBox.isSelected()) {
                        sb.append(checkBox.getText());
                    }
                }
                handleTopicAnswer(index - 1, sb.toString(), question);
            });
            options.getChildren().add(confirmLabel);
            options.getChildren().add(confirm);
        } else {
            ToggleGroup group = new ToggleGroup();
            RadioButton trueBtn = new RadioButton("正确");
            RadioButton falseBtn = new RadioButton("错误");
            trueBtn.setToggleGroup(group);
            falseBtn.setToggleGroup(group);
            trueBtn.setStyle("-fx-font-size: 14px;");
            falseBtn.setStyle("-fx-font-size: 14px;");

            if (userAnswers.containsKey(index - 1)) {
                String ans = userAnswers.get(index - 1);
                trueBtn.setSelected(ans.equals("A"));
                falseBtn.setSelected(ans.equals("B"));
            }

            trueBtn.setOnAction(e -> handleExamAnswer(index - 1, "A", question));
            falseBtn.setOnAction(e -> handleExamAnswer(index - 1, "B", question));
            options.getChildren().addAll(trueBtn, falseBtn);
        }
    }

    //换题栏
    private HBox switchQuestion() {
        HBox bottomBar = new HBox(20);
        bottomBar.setPadding(new Insets(20));
        bottomBar.setAlignment(Pos.BOTTOM_RIGHT);

        Button preBtn = new Button("上一题");
        preBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        preBtn.setMinWidth(100);
        Button nextBtn = new Button("下一题");
        nextBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        nextBtn.setMinWidth(100);
        Button submitBtn = new Button("交卷");
        submitBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        submitBtn.setMinWidth(100);

        preBtn.setOnAction(e -> showQuestion(questionIndex - 1));
        nextBtn.setOnAction(e -> {
            showQuestion(questionIndex + 1);
        });
        submitBtn.setOnAction(e -> {
            try {
                submitExam();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });

        bottomBar.getChildren().addAll(preBtn, nextBtn, submitBtn);
        return bottomBar;
    }

    private void handleExamAnswer(int questionIndex, String userAnswer, Questionlib question) {
        String userAnswer1 = (userAnswer == null || userAnswer.isEmpty()) ? null : userAnswer;
        userAnswers.put(questionIndex, userAnswer1);
        if (userAnswer1 == null) {
            unanswer++;
        } else if (userAnswer1.equals(question.getAnswer())) {
            correct++;
        } else {
            wrong++;
            if (wrong >= 11) {
                try {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setHeaderText("终止提醒");
                    alert.setContentText("已错11题以上，考试终止\n再点击确定可重新开始");
                    alert.showAndWait();
                    submitExam();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private void updateTime(int seconds) {
        int minutes = seconds / 60;
        int secs = seconds % 60;
        timeLabel.setText(String.format("剩余时间: %02d:%02d", minutes, secs));
    }

    private void createAnswers(Questionlib question) {
        Random r = new Random();
        String type = question.getType();
        String[] singleAnswer = {"A", "B", "C", "D"};
        String[] alotAnswer = {"AB", "AC", "AD", "BD", "BC", "ABC", "ABD", "ACD", "ABCD"};
        String[] panDuan = {"A", "B"};
        switch (type) {
            case "单选题":
                question.setAnswer(singleAnswer[r.nextInt(singleAnswer.length)]);
                break;
            case "多选题":
                question.setAnswer(alotAnswer[r.nextInt(alotAnswer.length)]);
                break;
            case "判断题":
                question.setAnswer(panDuan[r.nextInt(panDuan.length)]);
                break;
        }
    }

    private void startExam() {
        correct = 0;
        wrong = 0;
        unanswer = 0;
        remainTime = 2700;
        timeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> {
            remainTime--;
            updateTime(remainTime);
            if (remainTime <= 0) {
                try {
                    submitExam();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }

    private void submitExam() throws SQLException {
        timeline.stop();
        correct = 0;
        wrong = 0;
        unanswer = 0;
        wrongQuestionlibs = new ArrayList<>();
        for (int i = 0; i < examQuestions.size(); i++) {
            String userAnswer = userAnswers.get(i);
            String correctAnswer = examQuestions.get(i).getAnswer();
            Questionlib questionlib = examQuestions.get(i);
            if (userAnswer == null) {
                unanswer++;
            } else if (userAnswer.equals(correctAnswer)) {
                correct++;
            } else {
                wrong++;
                WrongQuestion wrongQuestion = new WrongQuestion();
                wrongQuestion.setAnswerId(-1);
                wrongQuestion.setQuestion(questionlib.getQuestion());
                wrongQuestion.setType(questionlib.getType());
                wrongQuestion.setTopic(questionlib.getTopic());
                wrongQuestion.setSection(questionlib.getSection());
                wrongQuestion.setAnswer(correctAnswer);
                wrongQuestion.setUserName(user.getUserName());
                wrongQuestionlibs.add(wrongQuestion);
                System.out.println("错题插入");
            }
        }
        int answerId = GradeUtil.addAnswer(user.getUserName(), correct, correct, wrong, (2700 - remainTime) / 60);
        for (WrongQuestion wrongquesion : wrongQuestionlibs) {
            int id = WrongUtil.addHighWrongQuestion(
                    answerId,
                    wrongquesion.getQuestion(),
                    wrongquesion.getType(),
                    wrongquesion.getTopic(),
                    wrongquesion.getSection(),
                    wrongquesion.getAnswer(),
                    user.getUserName()
            );
        }
        System.out.println("-----------------------");
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL);
        alert.setTitle("考试结果");
        alert.setHeaderText("考试结束，重新考试请点击’OK'，取消考试直接点取消");
        alert.setContentText(
                "得分：" + correct + "分\n" +
                        "答对：" + correct + "题\n" +
                        "答错：" + wrong + "题\n" +
                        "未答：" + unanswer + "题\n" +
                        "用时：" + (2700 - remainTime) / 60 + "分" + (2700 - remainTime) % 60 + "秒"
        );
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
            try {
                createExamUI(mainContent);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {
            mainContent.getChildren().clear();
        }
    }


    //历史成绩
    private void createHistoryGradeUI(StackPane rightPane) {
        VBox rightBox = new VBox();
        rightBox.setSpacing(10);
        Button button = new Button("查询");
        button.setStyle("-fx-background-color: #2f465e;-fx-text-fill: white;");
        grades = new TableView<>();
        grades.setMinHeight(100);
        TableColumn<Answer, Integer> answerId = new TableColumn<>("序号");
        answerId.setMinWidth(100);
        answerId.setCellValueFactory(cellData ->
                cellData.getValue().answerIdPro().asObject()
        );
        TableColumn<Answer, Integer> grade = new TableColumn<>("成绩");
        grade.setMinWidth(300);
        grade.setCellValueFactory(cellData ->
                cellData.getValue().gradePro().asObject()
        );
        TableColumn<Answer, Integer> correct = new TableColumn<>("答对题数");
        correct.setMinWidth(300);
        correct.setCellValueFactory(cellData ->
                cellData.getValue().correctPro().asObject()
        );
        TableColumn<Answer, Integer> wrong = new TableColumn<>("答错题数");
        wrong.setMinWidth(300);
        wrong.setCellValueFactory(cellData ->
                cellData.getValue().getWrongPro().asObject()
        );
        TableColumn<Answer, Integer> time = new TableColumn<>("用时");
        time.setMinWidth(300);
        time.setCellValueFactory(cellData ->
                cellData.getValue().timePro().asObject()
        );
        grades.getColumns().addAll(answerId, grade, correct, wrong, time);
        button.setOnAction(e -> {
            try {
                refreshAnswer();
                if (grades.getItems().isEmpty()) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setContentText("没有历史成绩呢，做个考试再来？");
                    alert.showAndWait();
                }
            } catch (SQLException ex) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("查询失败");
                alert.showAndWait();
                throw new RuntimeException(ex);
            }
        });

        rightBox.getChildren().addAll(grades, button);
        rightPane.getChildren().clear();
        rightPane.getChildren().add(rightBox);
        root.setCenter(rightPane);

    }

    private void refreshAnswer() throws SQLException {
        grades.getItems().clear();
        List<Answer> answers = GradeUtil.showGrade(user.getUserName());
        grades.getItems().addAll(answers);
    }

    //专项练习
    private void createTopicUI(StackPane rightPane) throws SQLException {
        userAnswers = new HashMap<>();
        correct = 0;
        wrong = 0;
        unanswer = 0;
        VBox questionArea = new VBox(15);
        questionArea.setStyle("-fx-text-alignment: center;");
        questionArea.setPadding(new Insets(20, 100, 20, 40));
        Label questionText = new Label();
        questionText.setWrapText(true);
        questionText.setStyle("-fx-font-size: 16px;-fx-text-alignment: center");
        options = new VBox(10);
        options.setPadding(new Insets(10, 0, 10, 20));
        questionArea.getChildren().addAll(questionText, options);
        ScrollPane scrollPane = new ScrollPane(questionArea);
        scrollPane.setFitToWidth(true);
        pane = new BorderPane();
        pane.setStyle("-fx-background-color: #f2eded");
        pane.setMinWidth(1050);
        pane.setCenter(scrollPane);
        HBox bottomBox = switchQuestion2();
        pane.setBottom(bottomBox);
        String s = searchTopic();
        if (s == null) {
            return;
        }
        topicQuestionlibs = new ArrayList<>();
        topicQuestionlibs = TestLib.selectTopicQuestions(s);
        showTopicQuestion(topicQuestionlibs, 1);
        rightPane.getChildren().clear();
        rightPane.getChildren().add(pane);
    }

    //日常练习换题lan
    private HBox switchQuestion2() {
        HBox bottomBar = new HBox(20);
        bottomBar.setPadding(new Insets(20));
        bottomBar.setAlignment(Pos.BOTTOM_RIGHT);

        Button preBtn = new Button("上一题");
        preBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        preBtn.setMinWidth(100);
        Button nextBtn = new Button("下一题");
        nextBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        nextBtn.setMinWidth(100);
        Button submitBtn = new Button("不写了");
        submitBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        submitBtn.setMinWidth(100);
        preBtn.setOnAction(e -> showTopicQuestion(topicQuestionlibs, questionIndex - 1));
        nextBtn.setOnAction(e -> showTopicQuestion(topicQuestionlibs, questionIndex + 1));
        submitBtn.setOnAction(e -> {
            try {
                sumTopicQuestion();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        bottomBar.getChildren().addAll(preBtn, nextBtn, submitBtn);
        return bottomBar;
    }

    private String searchTopic() {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("查询题目范畴");
        dialog.setHeaderText("请选择您要查询的题目范畴");
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK);
        HBox hbox = new HBox(10);
        hbox.setPadding(new Insets(0, 0, 10, 0));
        String[] topics = {"文字题", "图片题", "罚款题", "记分题"};
        Map<RadioButton, String> map = new HashMap<>();
        ToggleGroup group = new ToggleGroup();
        for (String topic : topics) {
            RadioButton radioButton = new RadioButton(topic);
            map.put(radioButton, topic);
            radioButton.setToggleGroup(group);
            hbox.getChildren().add(radioButton);
        }
        dialog.getDialogPane().setContent(hbox);
        dialog.setResultConverter(buttonType -> {
            if (buttonType == ButtonType.OK) {
                RadioButton radioButton = (RadioButton) group.getSelectedToggle();
                if (radioButton != null) {
                    String select = map.get(radioButton);
                    return select;
                } else {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setContentText("还没有选中对应的题目主题n");
                    alert.showAndWait();
                    return null;
                }
            }
            return null;
        });
        Optional<String> result = dialog.showAndWait();
        return result.orElse(null);
    }

    private void showTopicQuestion(List<Questionlib> questionlibs, int index) {
        Label confirmLabel=new Label("请在选完之后按确认选择");
        if (questionlibs.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText("温馨提示");
            alert.setContentText("这个主题的题库还没有题\n如果你是管理员，可以添加点这个主题的题目");
            alert.showAndWait();
            return;
        }
        if (!(index >= 1 && index <= questionlibs.size())) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText("温馨提示");
            alert.setContentText("太棒啦，关于这个范畴的题目你已经做完了呢");
            alert.showAndWait();
            return;
        }
        questionIndex = index;
        Questionlib question = questionlibs.get(index - 1);
        Label content = new Label(question.getQuestion());
        options.getChildren().add(content);
        String[] singleAnswer = {"A", "B", "C", "D"};
        if (question.getType().equals("单选题")) {
            ToggleGroup group = new ToggleGroup();
            for (int i = 0; i < singleAnswer.length; i++) {
                RadioButton rb = new RadioButton(singleAnswer[i]);
                rb.setToggleGroup(group);
                if (userAnswers.containsKey(index - 1)) {
                    rb.setSelected(rb.getText().startsWith(userAnswers.get(index - 1)));
                }
                rb.setOnAction(e -> handleTopicAnswer(index - 1, rb.getText().substring(0, 1), question));
                options.getChildren().add(rb);
            }
        } else if (question.getType().equals("多选题")) {
            List<CheckBox> checkBoxes = new ArrayList<>();
            for (int i = 0; i < singleAnswer.length; i++) {
                CheckBox cb = new CheckBox(singleAnswer[i]);
                if (userAnswers.containsKey(index - 1)) {
                    String answer = userAnswers.get(index - 1);
                    cb.setSelected(answer.contains(cb.getText()));
                }
                checkBoxes.add(cb);
                options.getChildren().add(cb);
            }
            Button confirm = new Button("确认选择");
            confirm.setStyle("-fx-background-color: #2f465e; -fx-text-fill: #edeef4;");
            confirm.setOnAction(e -> {
                StringBuilder sb = new StringBuilder();
                for (CheckBox checkBox : checkBoxes) {
                    if (checkBox.isSelected()) {
                        sb.append(checkBox.getText());
                    }
                }
                handleTopicAnswer(index - 1, sb.toString(), question);
            });
            options.getChildren().add(confirmLabel);
            options.getChildren().add(confirm);
        } else {
            ToggleGroup group = new ToggleGroup();
            RadioButton trueBtn = new RadioButton("正确");
            RadioButton falseBtn = new RadioButton("错误");
            trueBtn.setToggleGroup(group);
            falseBtn.setToggleGroup(group);
            trueBtn.setStyle("-fx-font-size: 16px;");
            falseBtn.setStyle("-fx-font-size: 16px;");

            if (userAnswers.containsKey(index - 1)) {
                String ans = userAnswers.get(index - 1);
                trueBtn.setSelected(ans.equals("A"));
                falseBtn.setSelected(ans.equals("B"));
            }
            trueBtn.setOnAction(e -> handleTopicAnswer(index - 1, "A", question));
            falseBtn.setOnAction(e -> handleTopicAnswer(index - 1, "B", question));
            options.getChildren().addAll(trueBtn, falseBtn);
        }
    }

    private void handleTopicAnswer(int questionIndex, String userAnswer, Questionlib question) {
        userAnswers.put(questionIndex, userAnswer);
        if (userAnswer.equals(question.getAnswer())) {
            correct++;
        } else {
            wrong++;
        }

    }

    private void sumTopicQuestion() throws SQLException {
        int correct = 0;
        int wrong = 0;
        int unanswer = 0;
        for (int i = 0; i < topicQuestionlibs.size(); i++) {
            String userAnswer = userAnswers.get(i);
            String correctAnswer = topicQuestionlibs.get(i).getAnswer();
            if (userAnswer == null) {
                unanswer++;
            } else if (userAnswer.equals(correctAnswer)) {
                correct++;
            } else {
                wrong++;
            }
        }
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL);
        alert.setTitle("练习结果");
        alert.setHeaderText("练习结束，重新开始请点击OK");
        alert.setContentText(
                "得分：" + correct + "分\n" +
                        "答对：" + correct + "题\n" +
                        "答错：" + wrong + "题\n" +
                        "未答：" + unanswer + "题\n"
        );
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
            createTopicUI(mainContent);
        } else {
            mainContent.getChildren().clear();
            return;
        }
    }

    //章节练习
    private void createSectionUI(StackPane rightPane) throws SQLException {
        userAnswers = new HashMap<>();
        VBox questionArea = new VBox(15);
        questionArea.setStyle("-fx-text-alignment: center;");
        questionArea.setPadding(new Insets(20, 100, 20, 40));
        Label questionText = new Label();
        questionText.setWrapText(true);
        questionText.setStyle("-fx-font-size: 16px;-fx-text-alignment: center");
        options = new VBox(10);
        options.setPadding(new Insets(10, 0, 10, 20));
        questionArea.getChildren().addAll(questionText, options);
        ScrollPane scrollPane = new ScrollPane(questionArea);
        scrollPane.setFitToWidth(true);
        pane = new BorderPane();
        pane.setStyle("-fx-background-color: #f2eded");
        pane.setMinWidth(1050);
        pane.setCenter(scrollPane);
        HBox bottomBox = switchQuestion3();
        pane.setBottom(bottomBox);
        String s = searchSection();
        if (s == null) {
            return;
        }
        sectionQuestionlibs = TestLib.selectSectionQuestions(s);
        if (sectionQuestionlibs.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText("温馨提示");
            alert.setContentText("这个主题的题库还没有题\n如果你是管理员，可以添加点这个主题的题");
            alert.showAndWait();
            return;
        }
        showTopicQuestion(sectionQuestionlibs, 1);
        rightPane.getChildren().clear();
        rightPane.getChildren().add(pane);
    }

    private String searchSection() {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("查询章节");
        dialog.setHeaderText("请选择您要查询的章节，总共6章");
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK);
        HBox hbox = new HBox(10);
        hbox.setPadding(new Insets(0, 0, 10, 0));
        String[] topics = {"1.驾驶证和机动车管理规定",
                "2.道路通行条件及通行规定",
                "3.道路交通安全违法行为及处罚",
                "4.道路交通事故处理相关规定",
                "5.机动车基础知识",
                "6.河南地方题"};
        Map<RadioButton, String> map = new HashMap<>();
        ToggleGroup group = new ToggleGroup();
        for (String topic : topics) {
            RadioButton radioButton = new RadioButton(topic);
            map.put(radioButton, topic);
            radioButton.setToggleGroup(group);
            hbox.getChildren().add(radioButton);
        }
        dialog.getDialogPane().setContent(hbox);
        dialog.setResultConverter(buttonType -> {
            if (buttonType == ButtonType.OK) {
                RadioButton radioButton = (RadioButton) group.getSelectedToggle();
                if (radioButton != null) {
                    String select = map.get(radioButton);
                    return select;
                } else {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setContentText("还没有选中对应的章节");
                    alert.showAndWait();
                    return null;
                }
            }
            return null;
        });
        Optional<String> result = dialog.showAndWait();
        return result.orElse(null);
    }

    private HBox switchQuestion3() {
        HBox bottomBar = new HBox(20);
        bottomBar.setPadding(new Insets(20));
        bottomBar.setAlignment(Pos.BOTTOM_RIGHT);

        Button preBtn = new Button("上一题");
        preBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        preBtn.setMinWidth(100);
        Button nextBtn = new Button("下一题");
        nextBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        nextBtn.setMinWidth(100);
        Button submitBtn = new Button("不写了");
        submitBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        submitBtn.setMinWidth(100);
        preBtn.setOnAction(e -> showTopicQuestion(sectionQuestionlibs, questionIndex - 1));
        nextBtn.setOnAction(e -> showTopicQuestion(sectionQuestionlibs, questionIndex + 1));
        submitBtn.setOnAction(e -> {
            try {
                sumSectionQuestion();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        bottomBar.getChildren().addAll(preBtn, nextBtn, submitBtn);
        return bottomBar;
    }

    private void sumSectionQuestion() throws SQLException {
        int correct = 0;
        int wrong = 0;
        int unanswer = 0;
        for (int i = 0; i < sectionQuestionlibs.size(); i++) {
            String userAnswer = userAnswers.get(i);
            String correctAnswer = sectionQuestionlibs.get(i).getAnswer();
            if (userAnswer == null) {
                unanswer++;
            } else if (userAnswer.equals(correctAnswer)) {
                correct++;
            } else {
                wrong++;
            }
        }

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("练习结果");
        alert.getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL);
        alert.setHeaderText("练习结束，重新开始请点击OK");
        alert.setContentText(
                "得分：" + correct + "分\n" +
                        "答对：" + correct + "题\n" +
                        "答错：" + wrong + "题\n" +
                        "未答：" + unanswer + "题\n"
        );
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
            createSectionUI(mainContent);
        } else {
            mainContent.getChildren().clear();
            return;
        }
    }

    //错题本
    private void createWrongUI(StackPane rightPane) {
        VBox rightBox = new VBox();
        rightBox.setSpacing(10);
        Button button = new Button("查询");
        button.setStyle("-fx-background-color: #2f465e;-fx-text-fill: white;");
        wrongQuestions = new TableView<>();
        wrongQuestions.setMinHeight(100);
        TableColumn<WrongQuestion, Integer> questionId = new TableColumn<>("错题序号");
        questionId.setMinWidth(100);
        questionId.setCellValueFactory(cellData ->
                cellData.getValue().questionIdPro().asObject()
        );
        TableColumn<WrongQuestion, Integer> answerId = new TableColumn<>("考试序号");
        answerId.setMinWidth(300);
        answerId.setCellValueFactory(cellData ->
                cellData.getValue().answerIdPro().asObject()
        );
        TableColumn<WrongQuestion, String> question = new TableColumn<>("题目");
        question.setMinWidth(300);
        question.setCellValueFactory(cellData ->
                cellData.getValue().questionPro()
        );
        TableColumn<WrongQuestion, String> section = new TableColumn<>("章节");
        section.setMinWidth(300);
        section.setCellValueFactory(cellData ->
                cellData.getValue().sectionPro()
        );
        TableColumn<WrongQuestion, String> topic = new TableColumn<>("题目范畴");
        topic.setMinWidth(300);
        topic.setCellValueFactory(cellData ->
                cellData.getValue().topicPro()
        );
        TableColumn<WrongQuestion, Integer> wrongCount = new TableColumn<>("错误次数");
        wrongCount.setMinWidth(100);
        wrongCount.setCellValueFactory(cellData ->
                cellData.getValue().wrongCountPro().asObject()
        );
        wrongQuestions.getColumns().addAll(questionId, answerId, question, section, topic, wrongCount);
        button.setOnAction(e -> {
            try {
                refreshWrong();
                if (wrongQuestions.getItems().isEmpty()) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setContentText("没有错题呢，你真棒！！！");
                    alert.showAndWait();
                }
            } catch (SQLException ex) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("查询失败");
                alert.showAndWait();
                throw new RuntimeException(ex);
            }
        });

        rightBox.getChildren().addAll(wrongQuestions, button);
        rightPane.getChildren().clear();
        rightPane.getChildren().add(rightBox);
        root.setCenter(rightPane);
    }

    private void refreshWrong() throws SQLException {
        wrongQuestions.getItems().clear();
        List<WrongQuestion> wrongQuestions1 = WrongUtil.getWrongQuestions(user.getUserName());
        wrongQuestions.getItems().addAll(wrongQuestions1);
    }


    //易错题练习
    private void createHighUI(StackPane rightPane) throws SQLException  {
        userAnswers = new HashMap<>();
        VBox questionArea = new VBox(15);
        questionArea.setStyle("-fx-text-alignment: center;");
        questionArea.setPadding(new Insets(20, 100, 20, 40));
        Label questionText = new Label();
        questionText.setWrapText(true);
        questionText.setStyle("-fx-font-size: 16px;-fx-text-alignment: center");
        options = new VBox(10);
        options.setPadding(new Insets(10, 0, 10, 20));
        questionArea.getChildren().addAll(questionText, options);
        ScrollPane scrollPane = new ScrollPane(questionArea);
        scrollPane.setFitToWidth(true);
        pane = new BorderPane();
        pane.setStyle("-fx-background-color: #f2eded");
        pane.setMinWidth(1050);
        pane.setCenter(scrollPane);
        HBox bottomBox = switchHighQuestions();
        pane.setBottom(bottomBox);
        highWrongQuestions = new ArrayList<>();
        highWrongQuestions = WrongUtil.showHighQuestion(user.getUserName(), 1);
        setHighWrongQuestions(highWrongQuestions, 1);
        rightPane.getChildren().clear();
        rightPane.getChildren().add(pane);
    }

    private HBox switchHighQuestions() {
        HBox bottomBar = new HBox(20);
        bottomBar.setPadding(new Insets(20));
        bottomBar.setAlignment(Pos.BOTTOM_RIGHT);

        Button preBtn = new Button("上一题");
        preBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        preBtn.setMinWidth(100);
        Button nextBtn = new Button("下一题");
        nextBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        nextBtn.setMinWidth(100);
        Button submitBtn = new Button("不写了");
        submitBtn.setStyle("-fx-background-color: #2f465e ;-fx-text-fill: white");
        submitBtn.setMinWidth(100);
        preBtn.setOnAction(e -> setHighWrongQuestions(highWrongQuestions, questionIndex - 1));
        nextBtn.setOnAction(e -> setHighWrongQuestions(highWrongQuestions, questionIndex + 1));
        submitBtn.setOnAction(e -> {
            try {
                sumWrongQuestion();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        bottomBar.getChildren().addAll(preBtn, nextBtn, submitBtn);
        return bottomBar;
    }

    private void sumWrongQuestion() throws SQLException {
        int correct = 0;
        int wrong = 0;
        int unanswer = 0;
        for (int i = 0; i < highWrongQuestions.size(); i++) {
            String userAnswer = userAnswers.get(i);
            String correctAnswer = highWrongQuestions.get(i).getAnswer();
            if (userAnswer == null) {
                unanswer++;
            } else if (userAnswer.equals(correctAnswer)) {
                correct++;
            } else {
                wrong++;
            }
        }

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("练习结果");
        alert.getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL);
        alert.setHeaderText("练习结束，重新开始请点击OK");
        alert.setContentText(
                "得分：" + correct + "分\n" +
                        "答对：" + correct + "题\n" +
                        "答错：" + wrong + "题\n" +
                        "未答：" + unanswer + "题\n"
        );
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
            createHighUI(mainContent);
        } else {
            mainContent.getChildren().clear();
            return;
        }
    }

    private void setHighWrongQuestions(List<WrongQuestion> wrongQuestions, int index) {
        if (wrongQuestions.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText("温馨提示");
            alert.setContentText("这个主题的题库还没有题");
            alert.showAndWait();
            return;
        }
        if (!(index >= 1 && index <= wrongQuestions.size())) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText("温馨提示");
            alert.setContentText("太棒啦，关于这个范畴的题目你已经做完了呢");
            alert.showAndWait();
            return;
        }
        questionIndex = index;
        WrongQuestion question = wrongQuestions.get(index - 1);
        Label content = new Label(question.getQuestion());
        options.getChildren().add(content);
        String[] singleAnswer = {"A", "B", "C", "D"};
        if (question.getType().equals("单选题")) {
            ToggleGroup group = new ToggleGroup();
            for (int i = 0; i < singleAnswer.length; i++) {
                RadioButton rb = new RadioButton(singleAnswer[i]);
                rb.setToggleGroup(group);
                if (userAnswers.containsKey(index - 1)) {
                    rb.setSelected(rb.getText().startsWith(userAnswers.get(index - 1)));
                }
                rb.setOnAction(e -> handleWrongAnswer(index - 1, rb.getText().substring(0, 1), question));
                options.getChildren().add(rb);
            }
        } else if (question.getType().equals("多选题")) {
            List<CheckBox> checkBoxes = new ArrayList<>();
            for (int i = 0; i < singleAnswer.length; i++) {
                CheckBox cb = new CheckBox(singleAnswer[i]);
                if (userAnswers.containsKey(index - 1)) {
                    String answer = userAnswers.get(index - 1);
                    cb.setSelected(answer.contains(cb.getText()));
                }
                checkBoxes.add(cb);
                options.getChildren().add(cb);
            }
            Button confirm = new Button("确认选择");
            confirm.setStyle("-fx-background-color: #2f465e; -fx-text-fill: #edeef4;");
            confirm.setOnAction(e -> {
                StringBuilder sb = new StringBuilder();
                for (CheckBox checkBox : checkBoxes) {
                    if (checkBox.isSelected()) {
                        sb.append(checkBox.getText());
                    }
                }
                handleWrongAnswer(index - 1, sb.toString(), question);
            });
            options.getChildren().add(confirm);
        } else {
            ToggleGroup group = new ToggleGroup();
            RadioButton trueBtn = new RadioButton("正确");
            RadioButton falseBtn = new RadioButton("错误");
            trueBtn.setToggleGroup(group);
            falseBtn.setToggleGroup(group);
            trueBtn.setStyle("-fx-font-size: 16px;");
            falseBtn.setStyle("-fx-font-size: 16px;");

            if (userAnswers.containsKey(index - 1)) {
                String ans = userAnswers.get(index - 1);
                trueBtn.setSelected(ans.equals("A"));
                falseBtn.setSelected(ans.equals("B"));
            }
            trueBtn.setOnAction(e -> handleWrongAnswer(index - 1, "A", question));
            falseBtn.setOnAction(e -> handleWrongAnswer(index - 1, "B", question));
            options.getChildren().addAll(trueBtn, falseBtn);
        }
    }

    private void handleWrongAnswer(int questionIndex, String userAnswer, WrongQuestion question) {
        userAnswers.put(questionIndex, userAnswer);
        if (userAnswer.equals(question.getAnswer())) {
            correct++;
        } else {
            wrong++;
        }

    }

}